#!/bin/sh /etc/rc.common
#
# Copyright (C) 2025 sirpdboy herboy2008@gmail.com https://github.com/sirpdboy/luci-app-watchdog
# 

START=99
STOP=90
USE_PROCD=1
config=watchdog
dir="/tmp/$config/"

start_service() {
    procd_open_instance
    enable_value=$(uci get $config.config.enable 2>/dev/null || echo "0")
    [ "$enable_value" -ne "0" ] && procd_set_param command /usr/share/$config/$config && echo "$config is starting now ..."
    procd_close_instance
}

reload_service() {
    stop
    sleep 1
    start
}

clear_rule(){

bin_nft=$(which nft 2>/dev/null)
bin_iptables=$(which iptables 2>/dev/null)
bin_ip6tables=$(which ip6tables 2>/dev/null)
if [ -x "$bin_nft" ] && [ -x /sbin/fw4 ]; then
    nftables_ver="true"
elif [ -x "$bin_iptables" ] || [ -x "$bin_ip6tables" ]; then
    iptables_ver="true"
fi

 if [ -n "$nftables_ver" ]; then
        nft delete rule inet fw4 watchdog_input ip saddr @watchdog_blacklist 2>/dev/null
        nft delete rule inet fw4 watchdog_input ip6 saddr @watchdog_blacklistv6 2>/dev/null
        nft delete rule inet fw4 watchdog_input ether saddr @watchdog_blacklistbridge 2>/dev/null
        nft delete chain inet fw4 watchdog_input 2>/dev/null
        nft delete set inet fw4 watchdog_blacklist 2>/dev/null
        nft delete set inet fw4 watchdog_blacklistv6 2>/dev/null
        nft delete set inet fw4 watchdog_blacklistbridge 2>/dev/null
    elif [ -n "$iptables_ver" ]; then
        iptables -D INPUT -m set --match-set watchdog_blacklist src -j DROP 2>/dev/null
        iptables -D INPUT -m set --match-set watchdog_range src -j DROP 2>/dev/null
        ip6tables -D INPUT -m set --match-set watchdog_blacklistv6 src -j DROP 2>/dev/null
        ipset destroy watchdog_blacklist 2>/dev/null
        ipset destroy watchdog_blacklistv6 2>/dev/null
        ipset destroy watchdog_range 2>/dev/null
    fi
}
stop_service() {
    [ -f ${dir}child_pid ] && parent_pid=$(cat ${dir}child_pid)
    clear_rule
    [ -n "$parent_pid" ] && {
        child_pids=$(pgrep -P $parent_pid)
        echo "Terminating child processes of $config..."
        for child_pid in $child_pids; do
            kill $child_pid
        done
    }
    local pids=$(ps | grep "$config" | grep -v grep | grep -v $$ | awk '{print $1}')
	[ -n "$pids" ] && echo "$pids" | xargs kill 2>/dev/null
    echo "Terminating $config process..."
}

service_triggers() {
    procd_add_reload_trigger $config
}
